package com.followmeandroid.util;

import android.net.Uri;

import com.followmeandroid.models.SingleToken;
import com.followmeandroid.models.Token;
import com.google.gson.GsonBuilder;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;

public class JSONHttpClient {
    //<T> T instead of int?

    public static <T> Integer PostObject(final String url, T object, Class<T> objectClass) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        int results = 0;
        try {

            StringEntity stringEntity = new StringEntity(new GsonBuilder().create().toJson(object));
            httpPost.setEntity(stringEntity);
            if(SingleToken.getToken() != null && SingleToken.getToken().getValid() == true && SingleToken.getToken().getAccess_token() != null){
                httpPost.setHeader("Authorization", SingleToken.getToken().getToken_type() + " " + SingleToken.getToken().getAccess_token());
            }

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");

                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                //return new GsonBuilder().create().fromJson(resultString, objectClass);
                results = httpResponse.getStatusLine().getStatusCode();
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }

    private static String convertStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }

    public static <T> T Get(String url, List<NameValuePair> params, final Class<T> objectClass) {
        HttpClient defaultHttpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        if (paramString.length() > 1) {
            url += "?" + paramString;
        } else {
            url += paramString;
        }

        HttpGet httpGet = new HttpGet(url);
        try {
            // header Auth { "Authorization": "Bearer " + token };
            httpGet.setHeader("Accept", "application/json");

            if(SingleToken.getToken() != null && SingleToken.getToken().getValid() == true && SingleToken.getToken().getAccess_token() != null){
                httpGet.setHeader("Authorization", SingleToken.getToken().getToken_type() + " " + SingleToken.getToken().getAccess_token());

            }

            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);

            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }

                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create().fromJson(resultString, objectClass);

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Integer Delete(String url, final List<NameValuePair> params) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpDelete httpDelete = new HttpDelete(url);

        HttpResponse httpResponse = null;
        try {
            httpResponse = defaultHttpClient.execute(httpDelete);
            return httpResponse.getStatusLine().getStatusCode();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public static Token Login(String url, String userName, String password) throws Exception {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
            Uri.Builder builder = new Uri.Builder();
            builder.scheme("")
                    .appendQueryParameter("grant_type", "password")
                    .appendQueryParameter("username", userName)
                    .appendQueryParameter("password", password);

            String submitLogin = builder.build().toString();
            submitLogin = submitLogin.substring(2);

            StringEntity stringEntity = new StringEntity(submitLogin);
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();

                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create().fromJson(resultString, Token.class);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

   /* {
        "access_token": "Pp37owoY0QlJPCBWdXZyhujxZU5POovKcyJ0BHSDDjJqL7KpJWC4FU79ZxbVbzBxddi4g40c3pUHWRIyDVcI3LW1AwpRou1jPvJQsb_yJS3j6OvNW85YH1Q1en6Oc5sWJZiWhMZR3ZTNR6mJ1CDAQ6SNMAStWZVcVgiM0Zdiil6c92HWAELIHQ0ObD7JPEZVsw4YR8vKJ_n2u27bu1kAQscmNwZfjCE8g5WIu10aHaH-bsmgIlQ_LNrImkooC4RVhvTfi5F61S8JaHO_24SZ63GTbAaFmP_ANMbTgnQYl-owSwhoG1yQDCCCHsjOqj5zGVcR-htmtrVmAuYap6rqWN7wFBQUxPqys4PhBXV8UHq7-te4YIkKdUTepL0_amKzvdoC5EXri4KsxW5ze-pLrLgEsg7YllhxUqiEi1Rzfoc",
            "token_type": "bearer",
            "expires_in": 1209599,
            "userName": "Adam",
            ".issued": "Mon, 10 Nov 2014 15:20:20 GMT",
            ".expires": "Mon, 24 Nov 2014 15:20:20 GMT"
    }*/

    public <T> int PostParams(String url, final List<NameValuePair> params, final Class<T> objectClass) {
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        return PostObject(url, null, objectClass);
    }
}

